<template>
  <div class="bigBox">
    <div style="position: relative;margin: 10px 0 0 20px;font-size: 18px;">
      <el-button :loading="downloadImgFlag" @click="downloadImgs(false)" class="downloadBtn">下载</el-button>
      <!-- <el-button :loading="downloadImgFlag" @click="downloadImgs(true)" class="downloadBtn">高清下载</el-button> -->
      <button :style="imgListRes.length == query.num ? 'display:none;height: 60px;' : 'margin-left:20px;height: 60px;'"
        @click="load()">加载更多</button>&nbsp;&nbsp;&nbsp;
      {{ "加载进度" + imgListRes.length + "/" + query.num }}&nbsp;&nbsp;&nbsp;
      {{ "已选择" + checkImgList.length + "张" }}&nbsp;&nbsp;&nbsp;
      <!-- {{ "当前良率" + (checkImgList.length / imgListRes.length * 100).toFixed(2) + "%" }} -->
    </div>
    <div v-infinite-scroll="load" infinite-scroll-delay="500" infinite-scroll-immediate="true"
      infinite-scroll-distance="100" class="infinite-list imgBox" style="overflow: auto">
      <span v-for="(data, index) in imgListRes" :key="index" class="imgSpan infinite-list-item" @click="checkItem(index)">
        <el-image style="width: 100%;" :src="data"
          :class="checkImgList.indexOf(index + 1) == -1 ? 'unSeleImg' : 'seleImg'" fit="scale-down" />
        <el-checkbox-group v-model="checkImgList">
          <el-checkbox :label="index + 1" />
        </el-checkbox-group>
      </span>
    </div>
    <div class="preView">
      <img :src="preImg" alt="">
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import $apiFun from "../../../request/api";
import axios from 'axios';
import { ElMessage } from 'element-plus'
import JSZip from 'jszip';
const router = useRouter();

const query = router.currentRoute.value.query
const checkImgList = ref([] as any)//选中的图片
const jsonData = reactive({
  data: {} as any
})//任务数据
const num = 10 //懒加载，每次加载几条
const loadFalg = ref(false)  //懒加载,加载标志
const imgList = reactive([] as any)//图片url数组
const imgListRes = reactive([] as any)//图片数据数组
const downloadImgFlag = ref(false)
const preImg = ref('')//预览图
const moreFlag = ref(true)

//懒加载
const load = async () => {
  if (!loadFalg.value) {
    if (imgList.length == 0 && imgListRes.length != 0 && moreFlag.value) {
      moreFlag.value = false
      ElMessage({
        message: '--------没有更多啦--------',
        type: 'success',
      })
    } else {
      console.log("正在获取更多")
      await formatImg(imgList.splice(0, 10))
    }
  }
}
//点击图片,审核
const checkItem = (index: number) => {
  preImg.value = imgListRes[index]
  //点击时自动勾选
  // if (checkImgList.value.indexOf(index + 1) == -1) {
  //   checkImgList.value.push(index + 1)
  // } else {
  //   checkImgList.value.forEach((element, index1) => {
  //     if (element == index + 1) {
  //       checkImgList.value.splice(index1, 1)
  //     }
  //   });
  // }
  console.log(index + 1, checkImgList.value)
}
//获取任务详情
const getTaskInfo = async () => {
  await $apiFun.ScriptTaskInfo({ spec: query }).then(async (res: any) => {
    if (res.code == 200) {
      let data = res.data
      jsonData.data = data
      jsonData.data.scenes[0].imgs.forEach(element => {
        imgList.push(element.url)
      });
      await load()
      checkItem(0)
    }
    console.log("获取任务详情", res);
  });
}
//将json数据格式化为base64图
const formatImg = async (imgList) => {
  loadFalg.value = true
  if (imgList.length > num) {
    imgList = imgList.splice(0, num)
  }
  //存储加载任务promise
  let primary = [] as any
  imgList.forEach((element) => {
    const taskInfo = new Promise((resolve) => {
      if (element.substring(element.length - 5) == '.json') {
        //服务器返回json文件
        axios({
          method: 'get',
          url: window.location.host.indexOf('pencil-stub.com') != -1 ? element : '/file-pencil' + element.substring(element.indexOf('/data/AiPaint')),
          responseType: 'json'
        }).then(response => {
          imgListRes.push('data:image/png;base64,' + response.data.substring(response.data.indexOf('/'), response.data.indexOf(', url=')))
          resolve("ok")
          // 进行进一步操作，如保存文件或处理文件内容
        })
      } else {
        //服务器返回其他格式文件
        axios.get(window.location.host.indexOf('pencil-stub.com') != -1 ? element : '/file-pencil' + element.substring(element.indexOf('/data/aiPaint')), { responseType: 'blob' })
          .then(response => {
            const reader = new FileReader();
            reader.onloadend = () => {
              const base64 = reader.result;
              imgListRes.push(base64)
              console.log(base64);
              resolve("ok")
            };
            reader.readAsDataURL(response.data);
          })
      }
    })
    primary.push(taskInfo)

  });
  //  全部图片加载完成
  await Promise.all(primary).then(() => {
    loadFalg.value = false
  })
  if (!preImg.value) preImg.value = imgListRes[0]
}
//下载到本地
const downloadImgs = async (hdFlag) => {
  if (checkImgList.value.length == 0) {
    ElMessage.error("请至少选择一个图片")
    return
  }
  downloadImgFlag.value = true
  // 创建一个用于存储图片的临时文件夹
  const tempFolder = new JSZip();
  let primary = [] as any//创建一个pomise合集
  //遍历选中的图片
  checkImgList.value.forEach((base64DataIndex: number) => {
    if (hdFlag) {
      //高清化处理
      const taskInfo = new Promise((resolve) => {
        let p = {
          spec: {
            image: imgListRes[base64DataIndex - 1],
            upscaling_resize: 2,
            type: 1
          }
        }
        //发起高清处理请求
        $apiFun.hdImg(p).then(async (res: any) => {
          if (res.code == 200) {
            // 创建一个新的文件名，例如image1.png, image2.png等
            const fileName = query.title + '_' + base64DataIndex + '.jpg';
            const base64Data = res.data.image
            const blob = b64toBlob(base64Data, 'image/jpeg');
            tempFolder.file(fileName, blob);
            resolve('ok')
          }
        })
      })
      primary.push(taskInfo)
    } else {
      // 创建一个新的文件名，例如image1.png, image2.png等
      const fileName = query.title + '_' + base64DataIndex + '.jpg';
      const base64Data = imgListRes[base64DataIndex - 1].split(',')[1];
      const blob = b64toBlob(base64Data, 'image/jpeg');
      tempFolder.file(fileName, blob);
    }
  })
  //  全部图片加载完成
  await Promise.all(primary).then(() => {
    console.log('所有图片处理完成')
  })
  console.log('开始制作压缩包')
  // 生成压缩包
  tempFolder.generateAsync({ type: 'blob' })
    .then((compressedBlob) => {
      // 创建一个下载链接
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(compressedBlob);
      downloadLink.download = query.title + '.zip';
      // 将链接添加到页面并模拟点击下载
      document.body.appendChild(downloadLink);
      downloadLink.click();
      // 清理临时文件（可选）
      tempFolder.remove(() => {
        console.log('临时文件已清理');
      });
      downloadImgFlag.value = false

    })
    .catch((error) => {
      console.error('压缩过程出错', error);
    });

  // // 创建一个新的文件名，例如image1.png, image2.png等
  // var fileName = query.title + '_' + base64Data + '.png';
  // // 移除base64 data uri前缀
  // var base64Data = imgListRes[base64Data - 1].split(',')[1];
  // // 将base64数据转换为Blob对象
  // var blob = b64toBlob(base64Data, 'image/png');
  // // 将Blob对象添加到压缩包中
  // tempFolder.file(fileName, blob);
  return

  //  全部图片加载完成
  // Promise.all(primary).then(() => {
  //   console.log('下载完成', primary.length)
  // })
}
//base64转图片（下载用）
const b64toBlob = (b64Data, contentType) => {
  contentType = contentType || '';
  var sliceSize = 512;
  var byteCharacters = atob(b64Data);
  var byteArrays = [] as any;

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
  }

  var blob = new Blob(byteArrays, { type: contentType });
  return blob;
}

onMounted(() => {
  if (!query.task_id) router.back()
  getTaskInfo()
})
</script>

<style scoped>
.downloadBtn {
  width: 114px;
  height: 40px;
  border-radius: 5px;
  background: rgba(255, 195, 0, 1);
  border: 1px solid rgba(255, 235, 59, 1);

  font-size: 16px;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
}

.unSeleImg {
  box-sizing: border-box;

}

.seleImg {
  box-sizing: border-box;
  border: 1px solid rgba(254, 197, 6, 1);
}

:deep(.imgSpan .el-checkbox__label, .imgSpan .is-checked) {
  color: rgba(254, 197, 6, 1);
}

:deep(.imgSpan .is-checked .el-checkbox__inner) {
  background-color: rgba(254, 197, 6, 1);
  border: 1px solid rgba(254, 197, 6, 1);
}

:deep(.imgSpan .el-checkbox__input .el-checkbox__inner:hover) {
  border-color: rgba(254, 197, 6, 1);
}

.imgSpan {
  display: inline-block;
  padding: 20px;
  width: 20%;
  box-sizing: border-box;
}

.el-checkbox-group {
  text-align: center;
}


.imgBox {
  height: 90%;
  overflow: auto;
  width: 50%;
  box-sizing: border-box;
  position: absolute;
  left: 0;
}

.preView {
  box-sizing: border-box;
  width: 50%;
  height: 90%;
  position: absolute;
  right: 0;
  text-align: center;
}

.preView img {
  max-height: 100%;
  max-width: 100%;
}

.bigBox {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
